﻿/*
本js用于房源编辑与添加的公共逻辑
本js依赖于RentAndSaleJson此对象,此对象在添加页面是js生成,在编辑页面是后台生成,此对象表示房源的租售信息
*/
var PropertyAddandEdit = new Class({
    //租售数据
    RentAndSaleJson: {},
    currentTrust: 0,
    //加裁租售数据
    LoadRentAndSaleJson: function () {
        (!this.RentAndSaleJson.RentTrust) && (this.RentAndSaleJson.RentTrust = {});
        (!this.RentAndSaleJson.SaleTrust) && (this.RentAndSaleJson.SaleTrust = {});
        this.RentAndSaleJson.RentTrust.PropertyRentTypeKeyIdOp = dataBind.getRealDataByType(32); //租赁方式
        this.RentAndSaleJson.RentTrust.PropertyRentPaymentTypeKeyIdOp = dataBind.getRealDataByType(33); //支付类型
        this.RentAndSaleJson.RentTrust.PropertyRentLimitKeyIdOp = dataBind.getRealDataByType(34); //出售详情
        this.RentAndSaleJson.SaleTrust.PropertySourceKeyIdOp = this.RentAndSaleJson.RentTrust.PropertySourceKeyIdOp = dataBind.getRealDataByType(22); //来源
        this.RentAndSaleJson.SaleTrust.PropertySituationKeyIdOp = this.RentAndSaleJson.RentTrust.PropertySituationKeyIdOp = dataBind.getRealDataByType(24); //现状
        this.RentAndSaleJson.SaleTrust.PropertySaleReasonKeyIdOp = dataBind.getRealDataByType(31); //出售原因
        this.RentAndSaleJson.SaleTrust.SeePropertyTimeTypeOp = this.RentAndSaleJson.RentTrust.SeePropertyTimeTypeOp = dataBind.getRealDataByType(65); //方便看房时间 
        this.RentAndSaleJson.SaleTrust.SeePropertyTimeBeginOp = this.RentAndSaleJson.RentTrust.SeePropertyTimeBeginOp = [{ ItemValue: 6, ItemText: "6:00" }, { ItemValue: 7, ItemText: "7:00" }, { ItemValue: 8, ItemText: "8:00" }, { ItemValue: 9, ItemText: "9:00" }, { ItemValue: 10, ItemText: "10:00" }, { ItemValue: 11, ItemText: "11:00" }, { ItemValue: 12, ItemText: "12:00" }, { ItemValue: 13, ItemText: "13:00" }, { ItemValue: 14, ItemText: "14:00" }, { ItemValue: 15, ItemText: "15:00" }, { ItemValue: 16, ItemText: "16:00" }, { ItemValue: 17, ItemText: "17:00" }, { ItemValue: 18, ItemText: "18:00" }, { ItemValue: 19, ItemText: "19:00" }, { ItemValue: 20, ItemText: "20:00" }, { ItemValue: 21, ItemText: "21:00" }, { ItemValue: 22, ItemText: "22:00" }, { ItemValue: 23, ItemText: "23:00" }, { ItemValue: 24, ItemText: "24:00" }];
        this.RentAndSaleJson.SaleTrust.SeePropertyTimeEndOp = this.RentAndSaleJson.RentTrust.SeePropertyTimeEndOp = this.RentAndSaleJson.SaleTrust.SeePropertyTimeBeginOp;
        //生成委托切换用到的div
        $('#tmplSaleRent').tmpl(this.RentAndSaleJson).appendTo("#delegateInfoModels");
    },
    //绑定页面其它的select,radio,checkbox
    loadOtherData: function () {
        dataBind.bindOption(8, "#HouseDirectionKeyId"); //朝向;
        dataBind.bindOption(4, "#PropertyTypeKeyId"); //建筑类型;
        dataBind.bindOption(3, "#PropertyUsageKeyId"); //房屋用途;
        dataBind.bindOption(53, "#selPropertyRightNatureKeyId"); //产权性质;
        dataBind.bindOption(23, "select[name=TrustorGenderKeyId]"); //;
        dataBind.bindOption(21, "select[name=TrustorTypeKeyId]"); //委托人类型
        dataBind.bindOption(79, "select[name=PropertyCardClass]"); //产别
        dataBind.bindOption(81, "select[name=EstateStatusKeyId]"); //楼盘状态
        dataBind.bindRadio(30, "#ParkingTypeKeyId", "ParkingTypeKeyId"); //车位
        dataBind.bindCheckBox(27, "#PropertyTagKeyIds", "PropertyTagKeyIds"); //标签
        dataBind.bindCheckBox(107, "#PropertyAttributeKeyIds", "PropertyAttributeKeyIds"); //房源属性
        dataBind.bindOption(38, "#selDecorationSituationKeyId");    //装修情况
        //如果修改成无效，暂缓则状态下方出现行家成交单选按纽
        if ($("#propertyStatus").val() == "2" || $("#propertyStatus").val() == "4") {

            dataBind.bindRadio(115, "#PropertyExpertTransactionKeyId", "ExpertTransaction"); //行家成交
        } else {
            $("#PropertyExpertTransactionKeyId").parent(".PropertyExpertTransaction").hide();
        }
        //$("#CommonConditionId").val($("#CommonConditionId").attr("bindvalue")); //共有情况
        $("#CountF").val($("#CountF").attr("bindvalue"));
        $("#CountT").val($("#CountT").attr("bindvalue"));
        $("#CountW").val($("#CountW").attr("bindvalue"));
        $("#CountY").val($("#CountY").attr("bindvalue"));
    },
    //普通事件绑定
    EventsBind: function () {
       
        //动态创建委托人
        $("#addtrustor").click(function () {
            if ($('#Trustordiv').children('div').length < 3) {
                var objItem = $('#hidDelegatePersonInfo').html();
                $("#Trustordiv").append(objItem);
                $.inputStatistics2($("#Trustordiv>div:last-child").find("textarea[name=TrustorsRemark]").first());
            } else {
                $.OKDialogAgency('<div class="tc">最多可添加3个联系人，如需添加，请删除一个联系人！</div>', '提示');
            }
        });

        //单价计算
        $("#consignConContent input[name=SalePrice]").live("blur", function () {
            if (!$("#Squaretxt").val()) {
                $("#danj1").html('0');
                $("#danj2").html('0');
                return false;
            }
            var temval = Number($(this).val()) / Number($("#Squaretxt").val()) * 10000;
            if (temval != 'Infinity' && !isNaN(temval)) {
                $("#danj1").html(temval.toFixed(2));
                $("#danj2").html(temval.toFixed(2));
            } else {
                $("#danj2").html('0');
                $("#danj1").html('0');
            }

        });
        $("#Squaretxt").bind("blur", function () {
            if (!$("#consignConContent input[name=SalePrice]").val()) {
                $("#danj2").html('0');
                $("#danj1").html('0');
                return false;
            }
            var temval = Number($("#consignConContent input[name=SalePrice]").val()) / Number($(this).val()) * 10000;
            if (temval != 'Infinity' && !isNaN(temval)) {
                $("#danj1").html(temval.toFixed(2));
                $("#danj2").html(temval.toFixed(2));
            } else {
                $("#danj2").html('0');
                $("#danj1").html('0');
            }
        });
        //委托按纽切换逻辑,IE高级版本同FF需要把属性值挂在attr上才能innerHTML出正确结果
        var TrustTyperadio = $("input[name=TrustType]");
        var temfn = this;
        TrustTyperadio.bind("click", function (e) {
            if (temfn.currentTrust == $(this).val()) {
                return;
            }
            temfn.currentTrust = $(this).val();
            var temvalue = this.value;
            var teminputs = $("#consignConContent").find("input[type=text]");
            teminputs.each(function () {
                this.setAttribute("value", this.value);
            });
            var temoption = $("#consignConContent").find("option");
            temoption.each(function () {
                if (this.selected) {
                    this.setAttribute("selected", this.selected);
                }
            });
            var temradio = $("#consignConContent").find("input[type=radio]");
            temradio.each(function () {
                if (this.checked) {
                    this.setAttribute("checked", this.checked);
                } else {
                    this.removeAttribute("checked");
                }
            });
            var temhtml = $("#consignConContent").html();
            $("#consignConContent").html("");
            if (temvalue == "1") {
                $("#consignConContent").append($("#saleTrustTmp"));
            } else if (temvalue == "2") {
                $("#consignConContent").append($("#rentTrustTmp"));
            } else {
                $("#consignConContent").append($("#bothTmp"));
                $("#bothTmp").find("input[name='RentPrice']").focus();
            }
            $("#delegateInfoModels").append(temhtml);
            //计算单价
            var saleprice = $("#saveProperyEditForm input[name=SalePrice]").val();
            var Square = $("#Squaretxt").val();
            var danj = (Number(saleprice) / Number(Square)) * 10000;
            if (danj != 'Infinity' && !isNaN(danj)) {
                $("#danj1").html(danj.toFixed(2));
                $("#danj2").html(danj.toFixed(2));
            } else {
                $("#danj1").html('0');
                $("#danj2").html('0');
            }
            temfn.linkShow();
            $.inputStatistics2("#saveProperyEditForm textarea[name=LaunchCondition]");

            //联动绑定事件
            agencyVerify.NumberRange("#saveProperyEditForm", "input[name='SalePrice']", $("#hidMinSalePrice").val(), '售价须大于或等于' + $("#hidMinSalePrice").val() + '万', "blur");
            agencyVerify.NumberRange("#saveProperyEditForm", "input[name='RentPrice']", $("#hidMinRentPrice").val(), '租价必须大于或等于' + $("#hidMinRentPrice").val() + '元/月', "blur");

        });
        //房型户型联动事件绑定
        $('#CountF').change(this.HouseRoomEventBind);

        //转介人智能提示
        $("#txtPropertyReferralOwnerName").autocomplete(function () {
            return "/property/user-auto-complete-obtain-ajax?name=" + escape($("#txtPropertyReferralOwnerName").val());
        }, {
            width: 260,
            max: 12,
            selectFirst: false,
            formatItem: function (row) {
                return row.UserName + "(" + row.EmployeeNo + ")<span style='float:right'>" + row.DepartmentName + "</span>";
            },
            formatResult: function (row) {
                return row.UserName;
            }
        }).result(function (a, b) {
            $("#txtPropertyReferralOwnerName").blur();
            $("#hidPropertyReferralOwner").val(b.UserKeyId);
            $("#hidPropertyReferralOwnerDeptKeyId").val(b.DepartmentKeyId);
        });
        $("#txtPropertyReferralOwnerName").change(function () {
            $("#hidPropertyReferralOwner").val("");
        });
        $("#delegatePersonInfo textarea[name=TrustorsRemark]").each(function () {
            $.inputStatistics2($(this));
        });

        //车位
        $("input[name='ParkingTypeKeyId']").bind("click", function (e) {
            var parkingType = $(this).attr("data-itemno");
            if (parkingType == "20" || parkingType == "30") {
                $("#divParkingNumber").show();

            } else {
                $("#divParkingNumber").hide();
            }
        });
    },
    //验证
    Verify: function () {
        //表单验证
        agencyVerify.greaterThanEqualZero("input[isZhengFu=1]", true);
        agencyVerify.nonnegativeIntInput("input[isint=1]", true);
        agencyVerify.nonnegativeInput("input[isfloat=1]", true);
        agencyVerify.greaterThanZeroInput("input[greater-than-zero=1]", true);
        agencyVerify.notdefaultSelect("#saveProperyEditForm", '#CountF', -1, "此项必选");
        agencyVerify.notdefaultSelect("#saveProperyEditForm", '#CountW', -1, "此项必选");
        agencyVerify.notdefaultSelect("#saveProperyEditForm", '#CountT', -1, "此项必选");
        agencyVerify.notdefaultSelect("#saveProperyEditForm", '#CountY', -1, "此项必选");
        agencyVerify.chooseAreaOrRealArea();
        agencyVerify.notdefaultSelect("#saveProperyEditForm", "#saveProperyEditForm #HouseDirectionKeyId", -1, "朝向必填", true);
        agencyVerify.notdefaultSelect("#saveProperyEditForm", "#saveProperyEditForm #PropertyUsageKeyId", -1, "房屋用途必填", true);
        agencyVerify.notdefaultSelect("#saveProperyEditForm", "#saveProperyEditForm #selPropertyRightNatureKeyId", -1, "产权性质必填", true);
        agencyVerify.notNullInput("#saveProperyEditForm", "#saveProperyEditForm :visible[isnull=isNull]", true, "blur");
        agencyVerify.notdefaultSelect("#saveProperyEditForm", "#delegatePersonInfo :visible[name=TrustorGenderKeyId]", -1, "必须选择联系人称谓！", true);
        agencyVerify.mobileInput("#saveProperyEditForm", "#saveProperyEditForm :visible[name=Mobile]", true);
        agencyVerify.notdefaultSelect("#saveProperyEditForm", '#saveProperyEditForm #PropertyRentPaymentTypeKeyId', -1, "此项必选", true);
        agencyVerify.bigOrSmallCompareAlert("#saveProperyEditForm", "#saveProperyEditForm select[name=SeePropertyTimeBegin]", "#saveProperyEditForm select[name=SeePropertyTimeEnd]", "结束时间必须大于开始时间", true);
        agencyVerify.notCheckedRadio("#saveProperyEditForm", '#consignConContent input[type=radio]', "请选择房源来源");        
        agencyVerify.NeedSmartTips("#saveProperyEditForm", "#txtPropertyReferralOwnerName", "#hidPropertyReferralOwner", "转介人必需从智能提示中选择", false);
        agencyVerify.NeedSmartTips("#saveProperyEditForm", "#txtDepartmentId", "#hidDepartmentId", "归属部门必需从智能提示中选择", false);
        agencyVerify.notNullInput("#saveProperyEditForm", "#txtDepartmentId", true, "blur");
        agencyVerify.NeedSmartTips("#saveProperyEditForm", "#txtPropertyChiefKeyId", "#hidUserId", "归属人必需从智能提示中选择", false);
	        agencyVerify.notNullInput("#saveProperyEditForm", "#txtPropertyChiefKeyId", true, "blur");
        //联动绑定事件
        agencyVerify.NumberRange("#saveProperyEditForm", "input[name='SalePrice']", $("#hidMinSalePrice").val(), '售价须大于或等于' + $("#hidMinSalePrice").val() + '万', "blur");
        agencyVerify.NumberRange("#saveProperyEditForm", "input[name='RentPrice']", $("#hidMinRentPrice").val(), '租价必须大于或等于' + $("#hidMinRentPrice").val() + '元/月', "blur");

    },
    //特殊验证
    SpeVerify: function () {
        $("#saveProperyEditForm").bind("submit", function () {
            for (var j = 0; j < PropertyFilterGrouped.PropertyStatus.length; j++) {
                if (PropertyFilterGrouped.PropertyStatus[j].code == $("#cmbPropertyStatus").val()) {
                    $("#PropertyStatusKeyId").val(PropertyFilterGrouped.PropertyStatus[j].Value);
                }
            }
            if ($('#EstateName').length > 0 && !($('#EstateName').val().length > 0)) {
                return false;
            }
            if ($('#BuildingName').length > 0 && !($('#BuildingName').val().length > 0)) {
                return false;
            }
            if ($('#EstateKeyId').length > 0 && !$('#EstateKeyId').val()) {
                $.OKCancelDialogAgency('<div class="tc">你的楼盘不是从下拉框选择出来的,是否继续？</div>', '提示', true, true, true);
            }
            if ($('#BuildingKeyId').length > 0 && !$('#BuildingKeyId').val()) {
                $.OKCancelDialogAgency('<div class="tc">你的栋座不是从下拉框选择出来的,是否继续？</div>', '提示', true, true, true);
            }
        });
        $("#HouseNo").bind("blur", function () {
            if ($('#BuildingKeyId').val() && $('#EstateKeyId').val() && $('#HouseNo').val()) {
                $.AjaxAgency('/Property/Property-house-number-check-ajax', { 'BuildingKeyId': $("#BuildingKeyId").val(), 'EstateKeyId': $("#EstateKeyId").val(), "HouseNo": $("#HouseNo").val() },
                    function (data) {
                        if (data == "exist") {
                            $.OKDialogAgency('<div class="tc">已存在相同房源！</div>', '提示', function () {
                                $("#HouseNo").select();
                            });
                        }
                    }
                );
            }
        });
    },
    //自动完成
    Autocomplete: function () {

    },
    //提交后事件
    successResult: function (data) {
        if (data.length == 36 || data == "ok") {
            var addcontinue = "";
            var prokeyid = "";
            if (data.length == 36) {
                addcontinue = '<a href="/property/property-add" class="btn-red mr10">继续新增</a>';
                prokeyid = data;
            }
            else {
                prokeyid = $("input[name=keyId]").val();
            }
            //弹出短信
            $.dialog({
                id: "dialogSms",
                lock: true,
                cancel: false,
                close: function () { window.close(); },
                content: '<p class="tc"><i class="icon-sigh"></i>保存成功！</p><div class="tc mt20">' + addcontinue + '<a class="btn-red mr10" id="seeInfoLink">查看本房源</a><a href="javascript:window.opener=null;window.open(\'\',\'_self\');window.close();" class="btn-gray">关闭当前页</a></div>'
            });
            $("#seeInfoLink").attr("href", "/property/details?keyId=" + prokeyid);
        } else {
            $.OKDialogAgency('<div class="tc">' + data + '</div>');
        }
    },
    //删除联系人
    delTrustor: function (e) {
        $(e).parent().remove();
    },
    //修改联系人手机号
    editTrustorMobile: function (e) {
        $.OKDialogAgency('<input id="artMobile" type="text" class="ipt w116" autocomplete="off" autocomplete="off"   mobleflag="mobleFlag" maxlength="11">'
            , "修改手机"
            , null
            , function () {
                if ($(".aui_content .wrong").length > 0) {
                    return false;
                } else {
                    var displayMobile = other.convertPhone(3,$("#artMobile").val());
                    var base = new Base64();
                    var hiddenMobile = base.encode($("#artMobile").val());
                    $(e).parent().find("span").html(displayMobile);
                    $(e).parent().find("[name=EditMobile]").val(hiddenMobile);
                }
            }
            , function () {
                //非空验证
                agencyVerify.notNullInput(".aui_content", "#artMobile", true, "blur");
                //0-9数字验证
                agencyVerify.greaterThanEqualZero("#artMobile", true);
                //手机号验证
                agencyVerify.mobileInput(".aui_content", "#artMobile", true, "blur");
            });
    },
    //修改联系人座机号
    editTrustorTelephone: function (e) {
        $.OKDialogAgency('<input id="artTelphone1" class="ipt w36" type="text" maxlength="4">\n\r<em class="horline">-</em>\n\r<input id="artTelphone2" class="ipt w86" type="text" size="8" maxlength="8">\n\r<em class="horline">-</em>\n\r<input id="artTelphone3" class="ipt w46" type="text" size="6" maxlength="6">'
            , "修改座机"
            , null
            , function () {
                
                if ($(".aui_content .wrong").length > 0) {
                    return false;
                } else {
                    var telephoneArray = [];
                    var displayTelphone = "";
                    if ($("#artTelphone1").val() != null && $("#artTelphone1").val()!="") {
                       // telephoneArray.push($("#artTelphone1").val());
                        displayTelphone += $("#artTelphone1").val()+"-";
                    }
                    if ($("#artTelphone2").val() != null && $("#artTelphone2").val() != "") {
                        //telephoneArray.push($("#artTelphone2").val());
                        displayTelphone += other.convertPhone(2, $("#artTelphone2").val());
                    }
                  
                    if ($("#artTelphone3").val() != null && $("#artTelphone3").val() != "") {
                       // telephoneArray.push($("#artTelphone3").val());
                        displayTelphone += "-" + $("#artTelphone3").val();
                    }
                    //displayTelphone = other.convertPhone($("#artTelphone2").val());
                    //displayTelphone = $("#artTelphone1").val()+"-"+displayTelphone+"-"+$("#artTelphone3").val()
                    var base = new Base64();
                    var hiddenTelphone2 = base.encode($("#artTelphone2").val());
                    $(e).parent().find("span").html(displayTelphone);
                    $(e).parent().find("[name=telphone1]").val($("#artTelphone1").val());
                    $(e).parent().find("[name=telphone2]").val(hiddenTelphone2);
                    $(e).parent().find("[name=telphone3]").val($("#artTelphone3").val());
                }
            }
            , function () {
                
               
                //非空验证
                agencyVerify.notNullInput(".aui_content", "#artTelphone2", true, "blur");
                //0-9数字验证
                agencyVerify.greaterThanEqualZero("#artTelphone1,#artTelphone2,#artTelphone3", true);
            });
        $("#artTelphone2").focus();
    },
    //选择租售
    chooseTrust: function () {
        var TrustTyperadio = $("input[name=TrustType]");
        TrustTyperadio[0].click();
    },
    //一些联动事件的显示和隐藏,方便看房时间显示,租期至,名称判断
    linkShow: function () {
        var temtext = $("#saveProperyEditForm select[name=SeePropertyTimeTypeKeyId]").find("option:selected").text();
        if (temtext == "请选择" || temtext == "时间不限") {
            $("#saveProperyEditForm span[name=SeePropertyTime]").hide();
        } else {
            $("#saveProperyEditForm span[name=SeePropertyTime]").show();
            $("#saveProperyEditForm select[name=SeePropertyTimeEnd]").show();
        }
        //temtext = $("#saveProperyEditForm select[name=PropertySituationKeyId]").find("option:selected").text();
        //if (temtext.indexOf("租客住") == -1) {
        //    $("#saveProperyEditForm span[name=rentToDateSpan]").hide();
        //} else {
        //    $("#saveProperyEditForm span[name=rentToDateSpan]").show();
        //}
    },
    //权限显示
    bindRight: function () {

    },
    //pageload
    PageLoad: function () {
        this.LoadRentAndSaleJson();
        this.loadOtherData();
        this.EventsBind();
        this.Verify();
        this.SpeVerify();
        this.Autocomplete();
        this.chooseTrust();
        this.linkShow();
        this.bindRight();
    }
});
//方便看房时间
PropertyAddandEdit.SeePropertyTimeTypeChange = function (el) {
    var temtext = $(el).find("option:selected").text();
    if (temtext == "请选择" || temtext == "时间不限") {
        $("#saveProperyEditForm span[name=SeePropertyTime]").hide();
    }
    else {
        $("#saveProperyEditForm span[name=SeePropertyTime]").show();
    }
}
//开始提交的确认逻辑
PropertyAddandEdit.formBegin = function () {


    if ($("#infosafe").attr("disabled") == "disabled") {
        return true;
    }
    else {
        if (($('input[name="Mobile"]').val() == "" && $('input[name="telphone2"]').val() == "" && $('#delegatePersonInfo').is(':hidden'))) {
            $.OKCancelDialogAgency('<div class="tc">该房源业主联系方式为空，是否现在保存？</div>', null, null, function () {
                other.buttonDisable('#infosafe', 'disabled');
                $("#saveProperyEditForm").submit();
            }, null);
            return false;
        }
        else {
            $.OKCancelDialogAgency('<div class="tc">是否确认提交？</div>', null, null, function () {
                other.buttonDisable('#infosafe', 'disabled');
                $("#saveProperyEditForm").submit();
            }, null);
            return false;
        }

    }
}
//租期至下拉选择
//PropertyAddandEdit.rentToDateChange = function (el) {
//    var temtext = $(el).find("option:selected").text();
//    if (temtext.indexOf("租客住") == -1) {
//        $("#saveProperyEditForm span[name=rentToDateSpan]").hide();
//    }
//    else {
//        $("#saveProperyEditForm span[name=rentToDateSpan]").show();
//    }
//}